<template>
  <div class="app-container">


    <!-- 单选 -->
    <div >
      <el-radio-group v-model="checkedRole">
        <el-radio v-for="role in roles" :label="role.id" :key="role.id">
          {{ role.roleName }}
        </el-radio>
      </el-radio-group>
    </div>

    <!-- </br> -->
    <el-button :disabled="saveBtnDisabled" type="primary" @click="update">
      保存
    </el-button>
  </div>
</template>

<script lang="ts" setup>
import {  ref } from 'vue'
import userApi from '@/api/acl/user'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import useCloseTag from "@/hooks/useCloseTag";


interface Role {
  id: number
  name: string
}

const { closeTag } = useCloseTag()
const route = useRoute()
const checkedRole = ref(null)
const roles = ref([] as Role[])
const userId = ref(null)
const saveBtnDisabled = ref(false)

/**
 * 页面初始化加载
 */
const init = () => {
  if (route.params && route.params.id) {
    userId.value = route.params.id as string
    getById(userId.value)
  }
}

/**
 * 获取所有角色和当前用户已经选择的角色
 * @param userId 用户id
 */
const getById = (userId: number) => {
  userApi.getAssign(userId).then(response => {
    checkedRole.value = response.data.assignRole

    roles.value = response.data.allRolesList
  })
}


/**
 * 保存修改
 */
const update = () => {

  // 非空判断
  if(checkedRole.value==null||checkedRole.value===""){
    ElMessage({
      type: 'error',
      message: '角色不能为空',
    })
    return
  }


  saveBtnDisabled.value = true // 防止表单重复提交
  
  // 修改权限
  userApi.saveAssign(userId.value, checkedRole.value).then(response => {
    ElMessage({
      type: 'success',
      message: '保存成功',
    })
    closeTag.value()

  })
}

init()
</script>